const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const mysql = require('mysql');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

handleError = function () {
  let db;
  db = mysql.createConnection({
    host: 'localhost',
    database: 'user',
    user: 'root',
    password: 'root',
  });
  //连接错误，2秒重试
  db.connect(function (err) {
    if (err) {
      setTimeout(handleError , 2000);
    }
  });

  db.on('error', function (err) {
    if (err.code === 'PROTOCOL_CONNECTION_LOST') {
      handleError();
    } else {
      console.log(err)
      handleError()
    }
  });
  return db;
};

let db;
app.all('*', function(req, res, next) {
  db = handleError()
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Credentials", "true");
  res.setHeader("Access-Control-Allow-Methods", "*");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
  res.setHeader("Access-Control-Expose-Headers", "*");
  next();
});
app.post('/login', (req, res, next) => {
  const userData = req.body.params;
  console.log(userData)
  db.query(`SELECT * FROM user where password = '${userData.password}' and account = '${userData.account}'`, (err, data) => {
    if (err) {
      const result = {
        code: 500,
        msg: '服务异常'
      };
      console.log(err);
      res.send(result);
      db.end()
    } else {
      const result = {
        code: 200,
        msg: '登录成功',
      };
      console.log(data);
      if (data.length < 1) {
        result.code = 500;
        result.msg = '账号不存在';
        res.send(result);
        db.end()
      } else {
        res.send(result);
        db.end()
      }
    }
  })
});
app.listen(3000, () => {
  console.log('server is running in post 3000')
});

